package micro.beauty.common.mvc.exception;

import micro.beauty.common.core.ResponseData;
import micro.beauty.common.core.ResponseUtil;
import micro.beauty.common.core.constant.SysRetCode;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
* @Description:    全局异常处理器
* @Author:         Liuliya
* @CreateDate:     2020/8/11 22:21
* @Version:        0.0.1
*/
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseData methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        for (ObjectError error : bindingResult.getAllErrors()) {
            return new ResponseUtil<>().error(error.getDefaultMessage());
        }
        return new ResponseUtil<>().error(
                SysRetCode.SYSTEM_ERROR.getCode(), SysRetCode.SYSTEM_ERROR.getMessage());
    }

    @ExceptionHandler(CommonException.class)
    public ResponseData commonException(CommonException e) {
        return new ResponseUtil<>().error(e.getMessage());
    }

}
